package com.springboot.activiti.web;

import org.activiti.engine.HistoryService;
import org.activiti.engine.IdentityService;
import org.activiti.engine.ProcessEngine;
import org.activiti.engine.RepositoryService;
import org.activiti.engine.RuntimeService;
import org.activiti.engine.TaskService;
import org.activiti.engine.history.HistoricProcessInstance;
import org.activiti.engine.history.HistoricTaskInstance;
import org.activiti.engine.repository.Deployment;
import org.activiti.engine.runtime.ProcessInstance;
import org.activiti.engine.runtime.ProcessInstanceQuery;
import org.activiti.engine.task.Task;
import org.activiti.engine.task.TaskQuery;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

/**
 * @Author: TongRui乀
 * @Date: 2019/2/22 11:27
 * @description： Activiti API接口
 */
@RestController
@RequestMapping("activiti")
public class ActivitiAPIController {

    @Autowired
    private RuntimeService runtimeService;

    @Autowired
    private TaskService taskService;

    @Autowired
    private IdentityService identityService;

    @Autowired
    private RepositoryService repositoryService;

    @Autowired
    private ProcessEngine processEngine;

    @Autowired
    private HistoryService historyService;


    /**
     *  部署工作流
     * @return
     */
    @RequestMapping("createProcess")
    public String createActiviProcess(){

        Deployment deploy = this.repositoryService.createDeployment()
                .addClasspathResource("test2.bpmn")
                .name("请假流程")
                .category("办公流程")
                .deploy();

        String result = "部署ID："+deploy.getId() + " 部署名称："+ deploy.getName();

        return result;
    }

    /**
     *  开始执行流程
     * @return
     */
    @RequestMapping("startProcess/{processId}")
    public String startProcess(@PathVariable String processId){

        ProcessInstance myProcess_1 = runtimeService.startProcessInstanceByKey(processId);

        String result = "工作流实例ID：" + myProcess_1.getId() + "  工作流程定义ID：" + myProcess_1.getProcessDefinitionId();

        // 设置流程变量
        this.runtimeService.setVariable(myProcess_1.getSuperExecutionId(), "level", "start");

        return result;
    }


    /**
     *  查询指定人的当前任务
     * @param assignee
     * @return
     */
    @RequestMapping("getAssigneeTask/{assignee}")
    public String getAssigneeTask(@PathVariable String assignee){

        TaskQuery taskQuery = this.taskService.createTaskQuery();

        List<Task> list = taskQuery.taskAssignee(assignee).list();

        StringBuilder sb = new StringBuilder();

        if(list != null && list.size() > 0){
            for (Task task: list) {

                sb.append("任务受理人：").append(task.getAssignee()).append("\n")
                        .append("任务ID：").append(task.getId()).append("\n")
                        .append("任务的名称：").append(task.getName()).append("\n");

            }
        }

        return sb.toString();
    }


    /**
     *  完成任务
     * @return
     */
    @RequestMapping("completeProcess/{taskId}")
    public String completeProcess(@PathVariable String taskId){

        this.processEngine.getTaskService().complete(taskId);

        String level = (String) this.runtimeService.getVariable(this.runtimeService.startProcessInstanceById("myProcess_1").getSuperExecutionId(), "level");

        return "任务："+ taskId +" 处理完毕！ 流程变量："+level;
    }


    /**
     *  查询正在执行的任务
     * @return
     */
    @RequestMapping("getRunningTask")
    public String getRunningTask(){

        TaskQuery taskQuery = this.taskService.createTaskQuery();

        List<Task> list = taskQuery.list();

        StringBuilder sb = new StringBuilder();

        if(list != null && list.size() > 0){
            for (Task task: list) {
                sb.append("任务受理人：").append(task.getAssignee()).append("\n")
                        .append("任务ID：").append(task.getId()).append("\n")
                        .append("任务的名称：").append(task.getName()).append("\n");
            }
        }

        return sb.toString();
    }


    /**
     *  获取工作流实例状态
     * @return
     */
    @RequestMapping("getProcessInstanceStatus/{instanceId}")
    public String getProcessInstanceStatus(@PathVariable String instanceId){

        ProcessInstanceQuery instanceQuery = this.runtimeService.createProcessInstanceQuery();

        ProcessInstance result = instanceQuery.processInstanceId(instanceId).singleResult();

        String res = "";

        if(result != null){
            res = instanceId + " 实例正在运行, 当前活动的任务:" + result.getActivityId();
        }else{
            res = instanceId + "应经结束";
        }

        return res;
    }


    /**
     *  获取所有的流程记录
     * @return
     */
    @RequestMapping("getProcessInstanceHistory")
    public String getProcessInstanceHistory(){

        List<HistoricProcessInstance> list = this.historyService.createHistoricProcessInstanceQuery().list();

        StringBuilder sb = new StringBuilder();

        if(list != null && list.size() > 0){
            for (HistoricProcessInstance instance: list) {
                sb.append("实例ID：").append(instance.getId()).append("--流程ID:")
                                    .append(instance.getProcessDefinitionId())
                                    .append("--流程开始时间：").append(instance.getStartTime())
                                    .append(" - ").append(instance.getEndTime())
                                                            .append("\n");
            }
        }

        return sb.toString();
    }


    @RequestMapping("getTaskInstanceHistory")
    public String getTaskInstanceHistory(){

        List<HistoricTaskInstance> list = this.historyService.createHistoricTaskInstanceQuery().list();

        StringBuilder sb = new StringBuilder();

        if(list != null && list.size() > 0){

            for (HistoricTaskInstance instance: list) {

                sb.append("任务ID：").append(instance.getId())
                        .append("--流程ID:").append(instance.getTaskDefinitionKey())
                        .append("--任务名称：").append(instance.getName())
                        .append("--任务执行人：").append(instance.getAssignee()).append("\n");

            }

        }

        return sb.toString();
    }


}
